<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增纸张调拨单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                纸张调拨单编码:
              </span>
              <el-tag>{{ form.allotNum }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="调拨单位" prop="unitname">
                    <el-input
                      v-model="form.unitname"
                      readonly
                      placeholder="请选择调拨单位"
                      @click="openDialog"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="调拨日期" prop="allotDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.allotDate"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      readonly
                      v-model="form.createTime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.allotRemark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="调拨明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">调拨明细</span>
          </template>
          <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
            >选择纸张</el-button
          >
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesAllotDetailList"
            :header-cell-class-name="must"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="调纸类型"
              min-width="120"
              align="center"
              prop="allotType"
              :show-overflow-tooltip="true"
            >
              <template v-slot="{ row }">
                <el-form-item
                  :prop="'mesAllotDetailList.' + row.$index + '.allotType'"
                  :rules="[
                    {
                      required: true,
                      message: '调纸类型',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-select
                    style="width: 100%"
                    :disabled="flag"
                    v-model="row.allotType"
                    class="m-2"
                    placeholder="请选择调纸类型"
                  >
                    <el-option
                      v-for="item in ems_allot_detail_allot_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="纸张编码"
              min-width="120"
              align="center"
              prop="code"
            />
            <el-table-column
              label="纸张名称"
              min-width="120"
              align="center"
              prop="name"
            />
            <el-table-column
              label="规格型号"
              min-width="120"
              align="center"
              prop="specs"
            >
              <template #default="scope">
                <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" prop="brand">
              <template #default="scope">
                <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
              </template>
            </el-table-column>
            <el-table-column
              label="定量"
              align="center"
              prop="weight"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="幅宽" align="center" prop="longWide" />
            <!-- <el-table-column label="宽度" align="center" prop="wide" /> -->
            <!-- <el-table-column label="高度" align="center" prop="height" /> -->
            <el-table-column
              label="单位"
              align="center"
              prop="unit"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120"
              prop="lnumber"
              :show-overflow-tooltip="true"
            >
              <template #header>
                <div>令/件<br />kg/卷筒</div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    v-model="scope.row.lnumber"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120"
              prop="jnumber"
              :show-overflow-tooltip="true"
            >
              <template #header>
                <div>件数<br />卷筒数</div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    v-model="scope.row.jnumber"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="odd">
              <template #header>
                <div>零头(令)<br />零头(kg)</div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    v-model="scope.row.odd"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="total">
              <template #header>
                <div>总数量(令)<br />总数量(kg)</div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    :disabled="flag"
                    v-model="scope.row.total"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              width="120"
              align="center"
              prop="detailRemark"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span v-if="flag">{{ scope.row.detailRemark }}</span>
                <el-form-item v-else>
                  <el-input
                    v-model="scope.row.detailRemark"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- 纸张选择 -->
    <SearchPaperS
      :visible="paperVisible"
      count
      @changeUpdate="changeData"
      @cancel="
        () => {
          paperVisible = false;
        }
      "
      :paperSelectList="paperSelectList"
    >
    </SearchPaperS>
    <SearchCustomer
      :visible="searchVisible"
      @changeUpdate="changeCustomerData"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchCustomer>
  </div>
</template>

<script setup>
import SearchPaperS from "@/components/SearchPaperS";
import SearchCustomer from "@/components/SearchCustomer";
import { toNumber } from "@/utils/ruoyi";
import {
  addAllotInfo,
  editAllotInfo,
  getAllotInfo,
} from "@/api/storage/transfer.js";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  mes_paper_brand,
  mes_paper_specs,
  ems_allot_detail_allot_type,
  mes_paper_unit,
} = proxy.useDict(
  "mes_paper_unit",
  "ems_allot_detail_allot_type",
  "mes_paper_brand",
  "mes_paper_specs"
);
const route = useRoute();
const router = useRouter();
const activeNames = ["1", "2"];
const userRef = ref(null);
const flag = ref(false);
const loading = ref(false);
const userInfo = useUserStore();
const paperVisible = ref(false);
const btnLoading = ref(false);
const search = ref({});
const paperSelectList = ref([]);
const searchVisible = ref(false);
const data = reactive({
  form: {},
  mesAllotDetailList: [],
  rules: {
    unitname: [
      { required: true, message: "调拨单位不能为空", trigger: "change" },
    ],
    allotDate: [
      {
        required: true,
        message: "调拨日期不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const must = (obj) => {
  let mustColumns = [1];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};

const { form, rules, mesAllotDetailList } = toRefs(data);

nextTick(() => {
  form.value.createBy = userInfo.name;
  form.value.picker = userInfo.name;
});
if (route.query.id) {
  getAllotInfo(route.query.id).then((res) => {
    Object.assign(form.value, { ...res.data });
    mesAllotDetailList.value = res.data.mesAllotDetailList.map((item) => {
      return {
        ...item.mesPaper,
        ...item,
        id: item.paperid,
        allotType: item.allotType?.toString() ?? "",
      };
    });
    if (route.query.info) {
      flag.value = true;
    }
  });
} else {
  flag.value = false;
  form.value = {};
  mesAllotDetailList.value = [];
}

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.warehousingDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
getCurrentDateTime();
// 总数量 合计
const changeSumTotal = (row, index) => {
  // if (row.lnumber && row.jumber && row.odd) {
  const count =
    Number(row.lnumber ? row.lnumber : 0) *
      Number(row.jnumber ? row.jnumber : 0) +
    Number(row.odd ? row.odd : 0);
  mesAllotDetailList.value[index].total = toNumber(count, 4);
  // if (count > row.quantity) {
  //     ElMessage({
  //         message: '总数量不能超过库存数量',
  //         type: 'warning ',
  //     })
  // }
  // }
};
// 打开客户页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选中的客户
const changeCustomerData = (row) => {
  form.value.allotUnitid = row.id;
  form.value.unitname = row.name;
  searchVisible.value = false;
};

// 新增入库明细
const handleAddStorage = () => {
  // if (route.query?.id) {
  paperSelectList.value = mesAllotDetailList.value;
  // }
  search.value = {
    supplierCode: form.value.supplierCode,
    paperType: form.value.paperType,
  };
  paperVisible.value = true;
};
// 选中的明细
const changeData = (row) => {
  const codeSet = new Set(mesAllotDetailList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      mesAllotDetailList.value.push({ ...item, paperid: item.id });
      codeSet.add(item.id);
    }
  });
  mesAllotDetailList.value = mesAllotDetailList.value.filter((item) =>
    row.some((rowItem) => rowItem.id === item.id)
  );
  paperVisible.value = false;
};

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    mesAllotDetailList.value = mesAllotDetailList.value.filter(
      (item) => item.id !== row.id
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 确认
const submitForm = () => {
  // const invalidData = mesAllotDetailList.value.find(data => data.total > data.quantity);
  // if (invalidData) {
  //     return ElMessage({
  //         message: '总数量不能超过库存数量',
  //         type: 'warning',
  //     });
  // }
  btnLoading.value = true;
  const inconformity = mesAllotDetailList.value.find((item) => {
    return !item.allotType;
  });

  if (inconformity) {
    btnLoading.value = false;
    ElMessage({
      message: "请填写调拨明细 调纸类型",
      type: "warning",
    });
    return;
  }
  userRef.value.validate((valid) => {
    if (valid) {
      if (route.query.id) {
        editAllotInfo({
          ...form.value,
          mesAllotDetailList: mesAllotDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      } else {
        addAllotInfo({
          ...form.value,
          status: 1,
          mesAllotDetailList: mesAllotDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      }
    } else {
      btnLoading.value = false;
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/transfer')
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}

.text {
  font-weight: 600;
  color: #666262;
}
</style>